<?php
namespace app\wechat\service;
use EasyWeChat\Factory;
use think\facade\Log;
use traits\controller\Jump;

/**
 * 小程序服务
 * Class MiniProgram
 * @package app\wechat\traits
 */
class MiniProgram
{
    protected $config;
    protected $minPrograme = [];
    public $app;
    public function __construct($config='')
    {
        $this->config      = $config;//get_option("wechat_official");
        $this->minPrograme = array_merge($this->config['minprogram'],config("official."));
        $this->app         = Factory::miniProgram($this->minPrograme);
    }

    /**
     * @Notes:根据 jsCode 获取用户 session 信息
     * @User: chenping
     * @email: 375129701@qq.com
     * return [
     *     openid: "oBGVb4xRt2-8t9NxOTZ7ybWzlfCgEefq"
     *     session_key: "ml6CHG1BNlQo3ZjCuIKGfgewFF=="
     * ]
     */
    public function getApp()
    {
        return $this->app;
    }


    /**
     * @Notes:根据 jsCode 获取用户 session 信息
     * @User: chenping
     * @email: 375129701@qq.com
     * return [
     *     openid: "oBGVb4xRt2-8t9NxOTZ7ybWzlfCgEefq"
     *     session_key: "ml6CHG1BNlQo3ZjCuIKGfgewFF=="
     * ]
     */
    public function getCode($JsCode)
    {
        return $this->app->auth->session($JsCode);
    }

    /**
     * @Notes:Token获取访问凭证
     * @User: chenping
     * @email: 375129701@qq.com
     * @return array
     */
    public function getAccessToken($refresh=false)
    {
        return $this->app->access_token->getToken($refresh);
    }



    /**
     * @Notes:Token获取访问凭证
     * @User: chenping
     * @email: 375129701@qq.com
     * @return array
     */
    public function setAccessToken( $token,  $lifetime = 7200)
    {
        return $this->app->access_token->setToken($token, $lifetime);
    }

    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     ** error code 说明.
     * <ul>
     *    <li>-41001: encodingAesKey 非法</li>
     *    <li>-41003: aes 解密失败</li>
     *    <li>-41004: 解密后得到的buffer非法</li>
     *    <li>-41005: base64加密失败</li>
     *    <li>-41016: base64解密失败</li>
     * </ul>
     * @return int 成功1，失败返回对应的错误码
     */
    public function decryptData($sessionKey, $encryptedData, $iv, &$data )
    {

        $config = $this->config['minprogram'];

        if (strlen($sessionKey) != 24)
        {
            return -41001;
        }
        $aesKey=base64_decode($sessionKey);
        if (strlen($iv) != 24)
        {
            return -41002;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );

        if( $dataObj  == NULL )
        {
            return -41003;
        }
        if( $dataObj->watermark->appid != $config['app_id'] )
        {
            return -41003;
        }
        $data = $result;
        return 1;
    }

    public function getUnlimit($users)
    {
        //$path = substr($path,0,strrpos($path,"=share"));
        //$path = substr($path,strripos($path,"=share")+6);
        //$param = json_decode($path,true);

        if($users['user_id'] == 'undefined' && $users['third_party_user_id'] == "undefined")  return "error";
        if(empty($users['user_id']) && empty($users['third_party_user_id']))  return "error";

        $user = "share=".$users['user_id']."_".$users['third_party_user_id'];

        Log::warning("share_code::"."5555"."user=".$user.'length'.strlen($user));

        $response = $this->app->app_code->getUnlimit($user, [
            'page'  => 'pages/shouye/shouye',
            'width' => 600,
        ]);
        return $response;
    }

}